package com.dxysun.springboot.convert;

import java.io.IOException;

import com.dxysun.springboot.dto.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

public class MyMessageConverter extends AbstractHttpMessageConverter
{
	private static final Log logger = LogFactory.getLog(MyMessageConverter.class);


	public MyMessageConverter()
	{
		// 新建一个我们自定义的媒体类型application/xxx-junlin
//		super(new MediaType("application", "xxx-junlin", Charset.forName("UTF-8")));
	}

	@Override
	protected boolean supports(Class clazz)
	{
		// 表明只处理UserEntity类型的参数。
//		return User.class.isAssignableFrom(clazz);
		return true;
	}

	/**
	 * 重写readlntenal 方法，处理请求的数据。代码表明我们处理由“-”隔开的数据，并转成 UserEntity类型的对象。
	 */
	@Override
	protected Object readInternal(Class clazz, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException
	{
//		String temp = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
//		String[] tempArr = temp.split("-");
		logger.info("MyMessageConverter  readInternal");
		User user = new User();
		user.setName("abcderg");
		user.setRemark("12334");
		return user;
	}

	/**
	 * 重写writeInternal ，处理如何输出数据到response。
	 */
	@Override
	protected void writeInternal(Object userEntity, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException
	{
		String out = "hello: MyMessageConverter";
		logger.info("MyMessageConverter  writeInternal");
		outputMessage.getBody().write(out.getBytes());
	}
}